<template>
  <div>
    <el-button type="primary" @click="onSubmit">发布APP</el-button>
    <el-table :data="appList" style="width: 100%">
      <el-table-column label="名称">
        <template slot-scope="scope">
          <router-link
            :to="{
              path: '/launch-app-detail',
              query: { id: scope.row.id, type: 4 }
            }"
            >{{ scope.row.name }}</router-link
          >
        </template>
      </el-table-column>
      <el-table-column label="logo">
        <template slot-scope="scope">
          <div class="img_logo">
            <img :src="scope.row.logo" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID">
        <template slot-scope="scope">
          <span>{{ scope.row.appId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新版本">
        <template slot-scope="scope">
          <span>{{
            `${scope.row.version}（${scope.row.versionNumber}）`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近发布时间">
        <template slot-scope="scope">
          <span>{{ scope.row.issueTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            :style="[
              { color: scope.row.status ? '#606266' : '#3E83F8' },
              { margin: 'margin: 0 5px 5px 0' }
            ]"
            size="mini"
            @click="changeStatus(scope.row)"
            >{{
              scope.row.status ? '已关闭，点击开启' : '已开启，点击关闭'
            }}</el-button
          >
          <el-button
            style="margin-left:0"
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            >发布新版本</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="Number(pagination.total)"
    >
    </el-pagination>
    <el-dialog :title="model.title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="APP名称"
          :label-width="formLabelWidth"
          prop="appName"
        >
          <el-input
            :disabled="model.id ? true : false"
            v-model="form.appName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="ID" :label-width="formLabelWidth" prop="appId">
          <el-input
            :disabled="model.id ? true : false"
            v-model="form.appId"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="安装包"
          :label-width="formLabelWidth"
          prop="downloadUrl"
        >
          <p style="margin: 0" v-if="fileName">{{ fileName }}</p>
          <el-upload
            action
            :http-request="importObj"
            :before-upload="beforeUploadImg"
            :show-file-list="false"
          >
            <el-button type="primary" :loading="uploadLoading" class="u-btn">{{
              form.downloadUrl ? '重新上传' : '上传安装包'
            }}</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="版本号"
          :label-width="formLabelWidth"
          prop="version"
        >
          <el-input v-model="form.version" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="构建号"
          :label-width="formLabelWidth"
          prop="versionNumber"
        >
          <el-input
            type="number"
            v-model="form.versionNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="forceUpdateStatus"
          label="是否强制更新"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="form.forceUpdateStatus"
            active-text="开"
            inactive-text="关"
            active-value="1"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="Logo" :label-width="formLabelWidth" prop="logo">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :http-request="uploadImg"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logo" :src="form.logo" class="avatar" />
            <span
              class="el-upload-list__item-delete"
              @click.stop="handleAvatarRemove()"
              v-if="form.logo"
              >x</span
            >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="更新内容"
          :label-width="formLabelWidth"
          prop="marks"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="form.marks"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="issueApp">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import base from '@/views/base.vue'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import { getAppList, issueApp, updateStatusApp } from '@/api/launch'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
import { ossUpload } from '@/api/api.js'
import treeVue from '../../../../components/tree/tree.vue'
export default {
  name: 'launch-app',
  // extends: base,
  data () {
    return {
      uploadLoading: false,
      fileName: '',
      url: '',
      dialogFormVisible: false,
      value: true,
      appList: [],
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      form: {
        remark: '',
        versionNumber: '',
        version: '',
        downloadUrl: '',
        appName: '',
        appId: '',
        logo: '',
        forceUpdateStatus: 0
      },
      model: {
        title: '',
        id: null,
        appName: '',
        appId: ''
      },
      formLabelWidth: '120px',
      rules: {
        appName: [
          { required: true, message: '请输入APP名称', trigger: 'blur' }
        ],
        appId: [{ required: true, message: '请输入ID', trigger: 'blur' }],
        marks: [{ required: true, message: '请输入更新内容', trigger: 'blur' }],
        versionNumber: [
          { required: true, message: '请输入构建号', trigger: 'blur' }
        ],
        forceUpdateStatus: [
          { required: true, message: '请选择是否强制更新', trigger: 'change' }
        ],
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
      }
    }
  },
  activated () {
    this.$store.dispatch('common/saveRegion')
    // this.getDataList("", "", "", "");
    this.queyEnumByTableName()
  },
  async created () {
    const res = await getAppList({
      type: 2,
      pageSize: this.pagination.pageSize,
      page: this.pagination.pageNum
    })
    this.appList = res[1].data
    this.pagination.total = Number(res[1].total)
  },
  computed: {},
  methods: {
    handleAvatarRemove () {
      this.form.logo = ''
    },
    async changeStatus (record) {
      console.log('record', record)
      this.$confirm(
        record.status
          ? `确定开启  ${record.name}  APP？`
          : `关闭后该APP无法使用，确定关闭  ${record.name}  APP？`,
        record.status ? '开启' : '关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          const res = await updateStatusApp({
            id: record.id,
            status: record.status ? 0 : 1
          })
          if (res[0]) {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          } else {
            const data = await getAppList({
              type: 2,
              pageSize: this.pagination.pageSize,
              page: this.pagination.pageNum
            })
            this.appList = data[1].data
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '操作成功!'
          // });
        })
    },
    async handleEdit (index, record) {
      ;(this.model.id = record.id), (this.model.title = '发布新版本')
      this.form.appName = record.name
      this.form.appId = record.appId
      this.dialogFormVisible = true
    },
    async issueApp () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.form.downloadUrl) {
            this.$message.error('安装包不能为空')
            return
          }
          if (!this.form.logo) {
            this.$message.error('封面不能为空')
            return
          }
          const res = await issueApp({
            id: this.model.id,
            ...this.form,
            type: 2
          })
          this.$message[res[0] ? 'error' : 'success'](
            res[0] ? '操作失败' : '操作成功'
          )
          if (res[0]) return
          const data = await getAppList({
            type: 2,
            pageSize: this.pagination.pageSize,
            page: this.pagination.pageNum
          })
          this.appList = data[1].data
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 批量导入
    async importObj (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'APK')
      if (res[0]) {
        return
      }
      console.log(res[1])
      this.form.downloadUrl = res[1].data.url
      this.fileName = res[1].data.fileName
      this.uploadLoading = false
      this.$refs.downloadUrl.clearValidate()
      // this.$ref.uploadExl.clearFiles();
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      this.uploadLoading = true
      console.log('file.type', file.type)
      const isExcel = file.type === 'application/vnd.android.package-archive'
      const isLt100M = file.size / 1024 / 1024 < 200
      console.log(file)
      if (!isExcel || !~file.name.indexOf('.apk')) {
        this.$message.error('上传的文件只能是 apk 格式!')
        this.uploadLoading = false
      }
      if (!isLt100M) {
        this.$message.error('上传的文件大小不能超过 200MB!')
        this.uploadLoading = false
      }
      return isExcel && isLt100M
    },
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'Launch')
      if (res[0]) {
        return
      }
      this.form.logo = res[1].data.url
      this.$refs.logo.clearValidate()
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    onSubmit () {
      this.dialogFormVisible = true
      this.model = {
        title: '发布APP',
        id: null,
        appName: '',
        appId: ''
      }
    },
    async handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagination.pageSize = val
      const res = await getAppList({
        type: 2,
        pageSize: this.pagination.pageSize,
        page: this.pagination.pageNum
      })
      this.appList = res[1].data
      this.pagination.total = res[1].total
    },
    async handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagination.pageNum = val
      const res = await getAppList({
        type: 2,
        pageSize: this.pagination.pageSize,
        page: this.pagination.pageNum
      })
      this.appList = res[1].data
      this.pagination.total = res[1].total
    },
    // 获取枚举
    async queyEnumByTableName () {
      // 获取学校的枚举接口
      let selectArr = {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      }
      let enumschoolallRes = await enumschoolall({})
      if (enumschoolallRes[0]) {
        return
      }
      this.selectArr = enumschoolallRes[1].data
      this.selectArr.level = [
        {
          label: 'A',
          value: 1
        },
        {
          label: 'B',
          value: 2
        },
        {
          label: 'C',
          value: 3
        }
      ]
      this.selectArr.coverageGrade = [
        {
          label: '幼儿园',
          value: 1
        },
        {
          label: '小学',
          value: 2
        },
        {
          label: '初中',
          value: 3
        },
        {
          label: '高中',
          value: 4
        }
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
.img_logo {
  width: 60px;
  img {
    width: 100%;
  }
}
</style>
